namespace Skymate.Commands
{
    using System.Collections.Generic;

    using Abp.Events.Bus;

    using Skymate.Lyjt.Core;

    using SuperSocket.Common;

    public class PhaseQueryResponseCommand : BaseLightCommand
    {
        public PhaseQueryResponseCommand()
            : base(ProtocolConst.OptionType.QueryResponse,
                ProtocolConst.ObjectType.Phase)
        {
        }

        public override void ExecuteCommand(LightAppSession session, SemaphoreRequestInfo requestInfo)
        {
            var message = $"相位查询应答";
            this.ShowLog(session.RemoteEndPoint.ToString(),
                message);
            
            var phases = this.Phases(requestInfo.Body);
            
            EventBus.Default.Trigger(new PhaseQueryResponseEvent(
            session.RemoteEndPoint.ToString(),
            phases));
            
        }

        private IEnumerable<Phase> Phases(byte[] buffer)
        {
            IList<Phase> result = new List<Phase>();
            var total = buffer[0];
            for (var i = 0; i < total; i++)
            {
                var buf = buffer.CloneRange(1 + Phase.BufferLength * i, Phase.BufferLength);
                var phase = Phase.CreatePhase(buf);
                if (phase != null)
                {
                    result.Add(phase);
                }
            }

            return result;
        }

    }
}